<template>
  <div class="main">
    <!-- 左侧搜索框和联系人列表 -->
    <div class="left">
      <!-- 搜索框 -->
      <div class="search">
        <svg-icon icon-class="search" class-name="search-icon" />
        <input
          v-model="searchValue"
          class="searchIpt"
          type="text"
          placeholder="请输入联系人姓名"
          @input="search"
        />
      </div>
      <!-- 联系人列表 -->
      <div class="userList">
        <el-scrollbar class="scrollbar" wrap-style="overflow-x:hidden;">
          <div
            v-for="item in itemList"
            :key="item.id"
            class="item"
            @click="clickUser(item)"
            :class="id === item.id ? 'active' : ''"
          >
            <h-badge :num="item.num" :max="3" >
              <img class="avatar" :src="item.avatar" alt="avatarImage" />
            </h-badge>
            <div class="itemRight">
              <div class="top">
                <span class="name">{{ item.name }}</span>
                <span class="time">{{ item.time }}</span>
              </div>
              <p class="content">{{ item.content }}</p>
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>
    <!-- 右侧消息区和编辑区 -->
    <div class="right">
      <p class="name">{{ userName }}</p>
      <div class="message">
        <el-scrollbar
          ref="myScrollbar"
          class="scrollbar"
          wrap-style="overflow-x:hidden;"
        >
          <div
            :class="item.type === 'you' ? 'itemLeft' : 'itemRight'"
            v-for="item in msgList"
            :key="item.id"
          >
            <img class="userAvatar" :src="item.avatar" alt="avatar" />
            <div class="messageMain">{{ item.content }}</div>
          </div>
        </el-scrollbar>
      </div>
      <div class="edit">
        <el-input
          @keyup.native="handleKeyUp"
          type="textarea"
          placeholder="请输入内容"
          v-model="message"
          ref="textInput"
          class="text-input"
          resize="none"
        >
        </el-input>
        <el-popover
          placement="top"
          trigger="manual"
          content="不能发送空白消息"
          popper-class="popper"
          v-model="isSend"
          :offset="10"
        >
          <h-button
            slot="reference"
            @click.native="send"
            size="mini"
            class="btn"
            type="success"
          >
            发送</h-button
          >
        </el-popover>
      </div>
    </div>
    <audio ref="messageAudio" controls style="display: none" muted>
      <source src="../../assets/mp3/message.wav" type="audio/wav" />
      您的浏览器不支持播放该音频文件。
    </audio>
    <button ref="btn" style="display: none"></button>
  </div>
</template>

<script>
// webScoket 在线测试地址 http://www.websocket-test.com/
/**
 * 由于浏览器无法在用户和页面未交互的时候进行自动播放音视频，所以在scoket链接成功后会模仿用户点击按钮，绕过浏览器限制。
 * 但是如果用户在此页面进行刷新，刷新之后还会重新链接scoket，但是这个时候无法通过模仿用户交互的方法绕过浏览器限制。导致音频无法播放。
 * beforeunload 只能给予用户提示，并不能阻止用户刷新页面。
 * 进入此页面会自动链接scoket，链接成功后服务器会发送一段消息，这个时候触发播放音频。
 */
export default {
  data() {
    return {
      searchValue: "",
      isScrolling: false,
      itemList: [
        {
          id: 1,
          num: 0,
          avatar: `https://picsum.photos/100/100?1`,
          name: "黄沛菡",
          time: "14:55",
          content: "你想喝什么饮料？矿泉水？可乐？还是啤酒？",
        },
        {
          id: 2,
          num: 10,
          avatar: `https://picsum.photos/100/100?2`,
          name: "张梦琪",
          time: "14:54",
          content: "你喝什么帮我来杯一样就行",
        },
        {
          id: 3,
          num: 2,
          avatar: `https://picsum.photos/100/100?3`,
          name: "李曼文",
          time: "14:53",
          content:
            "麻烦你给我发一下这个项目的需求文档，顺便将原型文件也发我，我看完之后再和你过一下",
        },
        {
          id: 4,
          num: 9,
          avatar: `https://picsum.photos/100/100?4`,
          name: "赵语蓉",
          time: "14:52",
          content: "明年一定哈哈哈哈",
        },
        {
          id: 5,
          num: "new",
          avatar: `https://picsum.photos/100/100?5`,
          name: "赖从彤",
          time: "14:51",
          content: "好的，谢谢赖总，赖总大气",
        },
        {
          id: 6,
          avatar: `https://picsum.photos/100/100?6`,
          name: "Cassiel",
          time: "14:50",
          content: "好嘞，约约约约约",
        },
        {
          id: 7,
          avatar: `https://picsum.photos/100/100?7`,
          name: "Mona",
          time: "14:49",
          content: "阿里的事又又又反转了",
        },
        {
          id: 8,
          avatar: `https://picsum.photos/100/100?8`,
          name: "Michelle",
          time: "14:48",
          content: "哈哈哈哈哈哈哈",
        },
        {
          id: 9,
          avatar: `https://picsum.photos/100/100?9`,
          name: "Rafael",
          time: "14:47",
          content: "你好，我是张阿姨介绍的",
        },
        {
          id: 10,
          avatar: `https://picsum.photos/100/100?10`,
          name: "Gabrielle",
          time: "14:46",
          content:
            "爱过，明天有事，没多少钱了，作业没写，这题不会，蓝翔，保大，救你，不后悔，不知道安利，吃酸奶舔盖，吃薯片不舔手指，不约，此刻我对你的伤害造成你心里阴影部分的面积约9平方厘米。请问还有什么要问的没",
        },
        {
          id: 11,
          avatar: `https://picsum.photos/100/100?11`,
          name: "Gabrielle",
          time: "14:46",
          content:
            "爱过，明天有事，没多少钱了，作业没写，这题不会，蓝翔，保大，救你，不后悔，不知道安利，吃酸奶舔盖，吃薯片不舔手指，不约，此刻我对你的伤害造成你心里阴影部分的面积约9平方厘米。请问还有什么要问的没",
        },
        {
          id: 12,
          avatar: `https://picsum.photos/100/100?12`,
          name: "Gabrielle",
          time: "14:46",
          content:
            "爱过，明天有事，没多少钱了，作业没写，这题不会，蓝翔，保大，救你，不后悔，不知道安利，吃酸奶舔盖，吃薯片不舔手指，不约，此刻我对你的伤害造成你心里阴影部分的面积约9平方厘米。请问还有什么要问的没",
        },
        {
          id: 13,
          avatar: `https://picsum.photos/100/100?13`,
          name: "Gabrielle",
          time: "14:46",
          content:
            "爱过，明天有事，没多少钱了，作业没写，这题不会，蓝翔，保大，救你，不后悔，不知道安利，吃酸奶舔盖，吃薯片不舔手指，不约，此刻我对你的伤害造成你心里阴影部分的面积约9平方厘米。请问还有什么要问的没",
        },
        {
          id: 14,
          avatar: `https://picsum.photos/100/100?14`,
          name: "Gabrielle",
          time: "14:46",
          content:
            "爱过，明天有事，没多少钱了，作业没写，这题不会，蓝翔，保大，救你，不后悔，不知道安利，吃酸奶舔盖，吃薯片不舔手指，不约，此刻我对你的伤害造成你心里阴影部分的面积约9平方厘米。请问还有什么要问的没",
        },
        {
          id: 15,
          avatar: `https://picsum.photos/100/100?15`,
          name: "Gabrielle",
          time: "14:46",
          content:
            "爱过，明天有事，没多少钱了，作业没写，这题不会，蓝翔，保大，救你，不后悔，不知道安利，吃酸奶舔盖，吃薯片不舔手指，不约，此刻我对你的伤害造成你心里阴影部分的面积约9平方厘米。请问还有什么要问的没",
        },
      ],
      userName: "",
      id: "",
      msgList: [
        {
          id: 1,
          avatar: `https://picsum.photos/100/100?1`,
          type: "my",
          time: "14:55",
          content: "你想喝什么饮料？矿泉水？可乐？还是啤酒？",
        },
        {
          id: 2,
          avatar: `https://picsum.photos/100/100?2`,
          type: "you",
          time: "14:54",
          content: "你喝什么帮我来杯一样就行",
        },
        {
          id: 3,
          avatar: `https://picsum.photos/100/100?1`,
          type: "my",
          time: "14:53",
          content:
            "麻烦你给我发一下这个项目的需求文档，顺便将原型文件也发我，我看完之后再和你过一下",
        },
        {
          id: 4,
          avatar: `https://picsum.photos/100/100?2`,
          type: "you",
          time: "14:52",
          content: "明年一定哈哈哈哈",
        },
        {
          id: 5,
          avatar: `https://picsum.photos/100/100?1`,
          type: "my",
          time: "14:51",
          content: "好的，谢谢赖总，赖总大气",
        },
        {
          id: 6,
          avatar: `https://picsum.photos/100/100?2`,
          type: "you",
          time: "14:50",
          content: "好嘞，约约约约约",
        },
        {
          id: 7,
          avatar: `https://picsum.photos/100/100?1`,
          type: "my",
          time: "14:49",
          content: "阿里的事又又又反转了",
        },
        {
          id: 8,
          avatar: `https://picsum.photos/100/100?22`,
          type: "you",
          time: "14:48",
          content: "哈哈哈哈哈哈哈",
        },
        {
          id: 9,
          avatar: `https://picsum.photos/100/100?1`,
          type: "my",
          time: "14:47",
          content: "你好，我是张阿姨介绍的",
        },
        {
          id: 10,
          avatar: `https://picsum.photos/100/100?2`,
          type: "you",
          time: "14:46",
          content:
            "爱过，明天有事，没多少钱了，作业没写，这题不会，蓝翔，保大，救你，不后悔，不知道安利，吃酸奶舔盖，吃薯片不舔手指，不约，此刻我对你的伤害造成你心里阴影部分的面积约9平方厘米。请问还有什么要问的没",
        },
        {
          id: 11,
          avatar: `https://picsum.photos/100/100?1`,
          type: "my",
          time: "14:46",
          content:
            "爱过，明天有事，没多少钱了，作业没写，这题不会，蓝翔，保大，救你，不后悔，不知道安利，吃酸奶舔盖，吃薯片不舔手指，不约，此刻我对你的伤害造成你心里阴影部分的面积约9平方厘米。请问还有什么要问的没",
        },
        {
          id: 12,
          avatar: `https://picsum.photos/100/100?2`,
          type: "you",
          time: "14:46",
          content:
            "爱过，明天有事，没多少钱了，作业没写，这题不会，蓝翔，保大，救你，不后悔，不知道安利，吃酸奶舔盖，吃薯片不舔手指，不约，此刻我对你的伤害造成你心里阴影部分的面积约9平方厘米。请问还有什么要问的没",
        },
        {
          id: 13,
          avatar: `https://picsum.photos/100/100?1`,
          type: "my",
          time: "14:46",
          content:
            "爱过，明天有事，没多少钱了，作业没写，这题不会，蓝翔，保大，救你，不后悔，不知道安利，吃酸奶舔盖，吃薯片不舔手指，不约，此刻我对你的伤害造成你心里阴影部分的面积约9平方厘米。请问还有什么要问的没",
        },
        {
          id: 14,
          avatar: `https://picsum.photos/100/100?2`,
          time: "14:46",
          type: "you",
          content:
            "爱过，明天有事，没多少钱了，作业没写，这题不会，蓝翔，保大，救你，不后悔，不知道安利，吃酸奶舔盖，吃薯片不舔手指，不约，此刻我对你的伤害造成你心里阴影部分的面积约9平方厘米。请问还有什么要问的没",
        },
        {
          id: 15,
          avatar: `https://picsum.photos/100/100?1`,
          time: "14:46",
          type: "my",
          content:
            "爱过，明天有事，没多少钱了，作业没写，这题不会，蓝翔，保大，救你，不后悔，不知道安利，吃酸奶舔盖，吃薯片不舔手指，不约，此刻我对你的伤害造成你心里阴影部分的面积约9平方厘米。请问还有什么要问的没",
        },
      ],
      message: "",
      isSend: false,
    };
  },
  created() {
    this.userName = this.itemList[0].name;
    this.id = this.itemList[0].id;
    //关闭连接
    // this.$sockets.close();
    // this.$sockets.onclose();
  },

  mounted() {
    this.$nextTick(() => {
      window.addEventListener("beforeunload", this.beforeUnload);
      this.$refs["myScrollbar"].wrap.scrollTop =
        this.$refs["myScrollbar"].wrap.scrollHeight;
      // 在 nextTick 回调中确保 DOM 已经更新
      // 建立 web socket 连接
      this.$sockets = new WebSocket("ws://124.222.224.186:8800");
      this.$sockets.onopen = () => {
        console.log("WebSocket 连接已打开");
        this.$refs.btn.click();
      };
      this.$sockets.onmessage = (event) => {
        console.log("收到消息：", event.data);
        this.$refs.messageAudio.play();
        this.$refs.messageAudio.muted = false;
      };
      this.$sockets.onclose = () => {
        console.log("WebSocket 连接已关闭");
      };
      this.$sockets.onerror = (error) => {
        console.error("WebSocket 发生错误：", error);
      };
    });
  },
  methods: {
    search() {
      console.log(`搜索了${this.searchValue}`);
    },
    clickUser(item) {
      this.userName = item.name;
      this.id = item.id;
      item.num = 0;
    },
    handleKeyUp(e) {
      if (e.key == "Enter" && e.ctrlKey == true) {
        // 获取输入框的 DOM 元素
        const inputElement = this.$refs.textInput.$el.querySelector("textarea");

        // 获取光标位置
        const cursorPosition = inputElement.selectionStart;

        // 在光标位置插入换行符
        this.message =
          this.message.slice(0, cursorPosition) +
          "\n" +
          this.message.slice(cursorPosition);

        // 将光标移动到新行的开头（通过移除刚才添加的空格）

        // 将光标移动到新的一行的开头
        inputElement.selectionStart = cursorPosition + 1;
        inputElement.selectionEnd = cursorPosition + 1;

        // 触发 input 事件，使 v-model 更新
        // this.$forceUpdate();
      } else if (e.key === "Enter") {
        e.preventDefault();
        this.send();
      }
    },
    send() {
      if (this.message.trim() === "") {
        this.isSend = true;
        setTimeout(() => {
          this.isSend = false;
        }, 1000);
      } else {
        this.$sockets.send(this.message);
        console.log(`向服务器发送了消息:${this.message}`);
        this.isSend = false;
        this.message = "";
      }
    },
    beforeUnload(event) {
      // 自定义你的提示信息
      const message = "你确定要离开吗？你的更改可能不会被保存。";

      // Firefox 需要设置 returnValue 属性
      if (event) {
        event.preventDefault();
        event.returnValue = message;
      }

      // Chrome, Safari 和 Opera 需要设置 returnValue 属性为一个非空字符串
      window.onbeforeunload = function () {
        return message;
      };
    },
  },
  beforeDestroy() {
    window.removeEventListener("beforeunload", this.beforeUnload);
    this.$sockets.close();
  },
};
</script>

<style lang="scss" scoped>
* {
  box-sizing: border-box;
}
.main {
  width: 70%;
  margin: 30px auto 0;
  height: calc(100vh - 130px);
  display: flex;
  // border: 1px solid black;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  border-radius: 10px;
  .left {
    width: 24%;
    height: 100%;
    display: flex;
    flex-direction: column;
    border-right: 1px solid #ccc;
    .search {
      height: 10%;
      border-bottom: 1px solid #ccc;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      background-color: #f7f7f7;
      .searchIpt {
        width: 90%;
        background-color: #f3f3f3;
        border-radius: 20px;
        border: 1px solid #ccc;
        height: 30px;
        padding-left: 36px;
      }
      .search-icon {
        position: absolute;
        z-index: 1;
        left: 30px;
      }
    }
    .userList {
      height: 90%;
      background-color: #e5e4e4;

      .item {
        width: 100%;
        display: flex;
        align-items: center;
        cursor: pointer;
        &:hover {
          background-color: rgb(211, 209, 209);
        }
        .avatar {
          width: 50px;
          height: 50px;
          border-radius: 10px;
          margin: 10px;
        }
        .itemRight {
          margin: 10px;
          margin-left: 0;
          height: 50px;
          display: flex;
          width: calc(100% - 80px);
          flex-direction: column;
          justify-content: space-around;
          .top {
            display: flex;
            justify-content: space-between;
            .name {
              font-size: 16px;
              color: #000;
            }
            .time {
              font-size: 14px;
              color: #ccc;
            }
          }
          .content {
            margin: 0;
            height: 20px;
            font-size: 12px;
            width: 100%;
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
            line-height: 20px;
            color: #acaaaa;
          }
        }
      }
      .active {
        background-color: rgb(211, 209, 209);
      }
    }
  }
  .right {
    width: 76%;
    height: 100%;
    background-color: #f5f5f5;
    .name {
      height: 10%;
      display: flex;
      margin: 0;
      padding-left: 20px;
      align-items: center;
      border-bottom: 1px solid #ccc;
    }
    .message {
      height: 70%;
      border-bottom: 1px solid #ccc;
      .itemLeft,
      .itemRight {
        display: flex;
        margin: 10px;
        .userAvatar {
          width: 30px;
          height: 30px;
          border-radius: 50%;
          display: flex;
        }
      }
      .itemLeft {
        .messageMain {
          font-size: 12px;
          max-width: 200px;
          padding: 10px;
          background-color: #fff;
          border-radius: 5px;
          margin-left: 10px;
          position: relative;
          z-index: 2;
          &::before {
            content: "";
            position: absolute;
            left: -5px;
            top: 10px;
            width: 15px;
            height: 15px;
            z-index: -1;
            transform: rotate(45deg);
            background-color: #fff;
          }
        }
      }
      .itemRight {
        flex-direction: row-reverse;
        .messageMain {
          font-size: 12px;
          max-width: 200px;
          padding: 10px;
          background-color: greenyellow;
          border-radius: 5px;
          margin-right: 10px;
          position: relative;
          z-index: 2;
          &::before {
            content: "";
            position: absolute;
            right: -5px;
            top: 10px;
            width: 15px;
            height: 15px;
            transform: rotate(45deg);
            background-color: greenyellow;
            z-index: -1;
          }
        }
      }
    }
    .edit {
      height: 20%;
      width: 100%;
      position: relative;
      .text-input {
        width: 100%;
        height: 100%;
      }
      .btn {
        position: absolute;
        bottom: 20px;
        right: 20px;
      }
    }
  }
}
.scrollbar {
  height: 100%;
}
/* 尝试隐藏刷新按钮，但请注意这不会在所有浏览器中起作用 */
#toolbar-refresh-button,
#refresh-button,
#navigator-toolbox > toolbarbutton[label="刷新"],
.refresh-button {
  display: none !important;
}
</style>
<style lang="scss">
// 滚动条圆角
.el-scrollbar__bar {
  border-radius: 6px;
}
// 滚动条hover后的背景色
.el-scrollbar__thumb {
  background-color: #ccc;
}
// 滚动条hover后的背景色
.el-scrollbar__thumb:hover {
  background-color: #ddd;
}
.el-textarea__inner,
.text-input {
  height: 100%;
  border: none;
  background-color: rgba(0, 0, 0, 0);
}
.popper {
  width: 100px !important;
  min-width: 120px !important;
  padding: 5px 10px;
  // padding: 0;
  color: #000;
  font-size: 12px;
}
</style>
